package cn.shone.hubu.common;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Session;

import net.sf.json.JSONObject;

import org.hibernate.HibernateException;
import org.hibernate.Query;

public class HibernatePage {
	
	private Session session;
	
	private String entityName;
	
	private List result;
	
	private int total;
	
	private int start;
	
	private int limit;
	
	
	public HibernatePage(Session session, String entityName, int start, int limit){
		this.session = session;
		this.entityName = entityName;
		this.start = start;
		this.limit = limit;
	}
	
	private Query setParamsAndQuery(JSONObject json, StringBuffer queryString, int start, int limit) throws HibernateException {
		Iterator keys = json.keys();
		List<Object> params = new ArrayList<Object>();
		String key = "";
		while(keys.hasNext()){
			key = (String)keys.next();
			queryString.append(String.format(" and t.%s=?", key));
			params.add(json.get(key));
		}
		Query query = session.createQuery(queryString.toString());
		if(limit != 0){
			query.setFirstResult(start);
			query.setMaxResults(limit);
		}
		for(int i=0;i<params.size();i++){
			query.setParameter(i, params.get(i));
		}
		return query;
	}
	
	private HibernatePage findByExample(JSONObject json){
		StringBuffer queryString = new StringBuffer();
		queryString.append(String.format("from %s t where 1=1", entityName));
		Query query = this.setParamsAndQuery(json, queryString, start, limit);
		result = query.list();
		total = this.countByExample(json);
		return this;
	}
	
	private int countByExample(JSONObject json){
		StringBuffer queryString = new StringBuffer();
		queryString.append(String.format("select count(*) from %s t where 1=1 ", entityName));
		Query query = setParamsAndQuery(json, queryString, 0, 0);
		return ((Integer) query.iterate().next()).intValue();
	}
	
	public static HibernatePage findByExample(Session session, String entityName, JSONObject json, int start, int limit){
		HibernatePage hp = new HibernatePage(session, entityName, start, limit);
		return hp.findByExample(json);
	}

	public String getEntityName() {
		return entityName;
	}

	public int getLimit() {
		return limit;
	}

	public List getResult() {
		return result;
	}

	public Session getSession() {
		return session;
	}

	public int getStart() {
		return start;
	}

	public int getTotal() {
		return total;
	}
	
}
